package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * Selector1类
 * 实现选择器1的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class Selector1 implements AxdrType {

    private byte[] dataCode = null;
    private OAD oad = null;
    private Data data = null;

    /**
     * 默认构造函数
     */
    public Selector1() {
    }

    /**
     * 设置数据编码
     * 
     * @param dataCode 数据编码
     */
    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    /**
     * 设置所有参数
     * 
     * @param oad  对象属性描述符
     * @param data 数据
     */
    public void setAll(OAD oad, Data data) {
        this.oad = oad;
        this.data = data;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        int codeLength = 0;

        oad = new OAD();
        codeLength += oad.decode(input);

        data = new Data();
        codeLength += data.decode(input);

        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        int codeLength;

        if (dataCode != null) {
            codeLength = dataCode.length;
            for (int i = dataCode.length - 1; i >= 0; i--) {
                try {
                    output.write(dataCode[i]);
                } catch (java.io.IOException e) {
                    throw new RuntimeException("IO exception during encode", e);
                }
            }
        } else {
            if (oad != null && data != null) {
                codeLength = 0;
                codeLength += data.encode(output);
                codeLength += oad.encode(output);
            } else {
                throw new RuntimeException("oad or data is null");
            }
        }
        return codeLength;
    }

    /**
     * 编码并保存
     * 
     * @param encodingSizeGuess 编码大小预估
     */
    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    /**
     * 获取对象属性描述符
     * 
     * @return 对象属性描述符
     */
    public OAD getOad() {
        return oad;
    }

    /**
     * 获取数据
     * 
     * @return 数据
     */
    public Data getData() {
        return data;
    }

    @Override
    public String toString() {
        if (oad != null && data != null) {
            return "sequence: {" + "oad: " + oad + ", data: " + data + "}";
        } else {
            return "oad or data is null";
        }
    }
}